import React from 'react';

const ThemeContent = React.createContext(null);


class Doing extends React.Component {
  constructor(props){
    super(props)
  }
  static contextType = ThemeContent;
  render() {
    const theme = this.context; // react 会向上找最近的 provider
    return <p>Doing: theme  {theme}</p>
  }
}

function Done(props) {
  
  return  <ThemeContent.Consumer>
      {value => <p>Done: theme  {value}</p>}
    </ThemeContent.Consumer>
}

function TodoList(props) {
  return (
    <div>
        <Doing/>
        <Done/>
    </div>
  )
}

class ContextComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      theme: 'light'
    }
    this.themeRef = React.createRef();
  }
  render() {
    return <ThemeContent.Provider value={this.state.theme}>
        <p>{this.state.theme}</p>
        <input defaultValue ={this.state.theme} ref={this.themeRef}/>
        <button onClick= {this.changeTheme}>change Theme</button>
        <hr/>
        <TodoList/>
    </ThemeContent.Provider>
    
  }
  changeTheme = () =>{
    const currentVal = this.themeRef.current.value;
    const theme = currentVal === 'light'? 'dark': 'light'
    this.setState({
      theme
    })
  }
}

export default ContextComponent